#!/bin/sh

if [ -z "$1" ]; then
  echo "parameter missing! pls confirm the parameter is action name."
  exit 1
fi

ROOT_PATH=/home/web/framework
CORESEEK_PATH=/usr/local/coreseek
MMSEG3_PATH=/usr/local/mmseg3
CSFT_FILE=${ROOT_PATH}/backend/coreseek/csft_mysql.conf

#searchd 运行后生成的pid file，注意：要同csft config文件一样
#SEARCHD_PID_FILE=${CORESEEK_PATH}/var/log/searchd_mysql.pid
SEARCHD_PID_FILE=${ROOT_PATH}/logs/coreseek/searchd_mysql.pid


UNIGRAM_PATH=${ROOT_PATH}/backend/coreseek
UNIGRAM_NAME=unigram.txt
UNIGRAM_FILE=${UNIGRAM_PATH}/${UNIGRAM_NAME}

THESAURUS_PATH=${ROOT_PATH}/backend/coreseek
THESAURUS_NAME=thesaurus.txt
THESAURUS_FILE=${THESAURUS_PATH}/${THESAURUS_NAME}


start_searchd() {
    ${CORESEEK_PATH}/bin/searchd -c ${CSFT_FILE} --pidfile 
    chmod 777 ${SEARCHD_PID_FILE}
}

stop_searchd() {
    ${CORESEEK_PATH}/bin/searchd -c ${CSFT_FILE} --stop
}

gen_uni() {
    #cd ${MMSEG3_PATH}/etc
    ${MMSEG3_PATH}/bin/mmseg -u ${UNIGRAM_FILE}
    mv -f ${UNIGRAM_FILE}.uni ${MMSEG3_PATH}/etc/uni.lib
    chmod 777 ${MMSEG3_PATH}/etc/uni.lib
}

gen_thesaurus() {
    cd ${MMSEG3_PATH}/etc
    ${MMSEG3_PATH}/bin/mmseg -t ${THESAURUS_FILE}
    chmod 777 ${MMSEG3_PATH}/etc/thesaurus.lib
}

gen_index() {
    gen_uni
    gen_thesaurus
    if [ -f ${SEARCHD_PID_FILE} ]; then
        ${CORESEEK_PATH}/bin/indexer -c ${CSFT_FILE} --all --rotate
    else
        ${CORESEEK_PATH}/bin/indexer -c ${CSFT_FILE} --all
    fi
}

get_status() {
    if [ -f ${SEARCHD_PID_FILE} ]; then
        echo "searchd service is running!"
        echo PID: `cat ${SEARCHD_PID_FILE}`
    else
        echo "searchd service not found!"        
    fi
}

case $1 in
    start)
        start_searchd
    ;;
    stop)
        stop_searchd
    ;;
    restart)
        stop_searchd
        sleep 1
        echo ""
        start_searchd
    ;;
    genindex)
        gen_index
    ;;
    genuni)
        gen_uni
    ;;
    genthesaurus)
        gen_thesaurus
    ;;
    status)
        get_status
    ;;
    *)
        echo action name: \"$1\" Invalid!
	    echo "the action name must among the commands [ start | stop | genindex | genuni | genthesaurus ]."
    ;;
esac
